﻿using System;
using System.Text.RegularExpressions;

namespace BlogDemo.Common
{
    class AntiSqlInject
    {
        /// <summary>
        /// 判断字符串中是否有SQL攻击代码
        /// true-安全；false-有注入攻击现有
        /// </summary>
        /// <param name="inputString">传入用户提交数据</param>
        /// <returns></returns>
        public static bool ProcessSqlStr(string inputString)
        {
            string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
            try
            {
                if ((inputString != null) && (inputString != String.Empty))
                {
                    string str_Regex = @"\b(" + SqlStr + @")\b";

                    Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase);
                    if (true == Regex.IsMatch(inputString))
                        return false;

                }
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 过滤特殊字符和关键字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FilterSql(string s)
        {
            if (string.IsNullOrEmpty(s)) return string.Empty;
            s = s.Trim().ToLower();
            s = s.Replace("=", "");
            s = s.Replace("'", "");
            s = s.Replace(";", "");
            s = s.Replace(" or ", "");
            s = s.Replace("and", "");
            s = s.Replace("exec", "");
            s = s.Replace("execute", "");
            s = s.Replace("insert", "");
            s = s.Replace("delete", "");
            s = s.Replace("update", "");
            s = s.Replace("alter", "");
            s = s.Replace("create", "");
            s = s.Replace("drop", "");
            s = s.Replace("count", "");
            s = s.Replace("char", "");
            s = s.Replace("mid", "");
            s = s.Replace("substring", "");
            s = s.Replace("master", "");
            s = s.Replace("truncate", "");
            s = s.Replace("declare", "");
            s = s.Replace("xp_cmdshell", "");
            s = s.Replace("restore", "");
            s = s.Replace("net +user", "");
            s = s.Replace("backup", "");
            s = s.Replace("net +localgroup", "");
            s = s.Replace("net +localgroup +administrators", "");
            s = s.Replace("%", "");
            s = s.Replace("--", "");
            s = s.Replace("xp_", "");
            return s;
        }
    }
}
